﻿using UnityEngine;
using System.Collections.Generic;
using System;

public delegate void NetworkEvent(ByteBuffer buffer);

public class NetworkManager : MonoBehaviour {

    private static NetworkManager _instance;
    public static NetworkManager Instance
    {
        get
        {
            return _instance;
        }
    }

    SocketClient client;
    private int HeartInterval = 5;

    //存储子线程的消息体
    Queue<ByteBuffer> queue = new Queue<ByteBuffer>();
    

    private void Awake()
    {
        _instance = this;

        client = new SocketClient();

        EventManager.HeartBeat += OnHeartBeat;
    }
    private void OnDestroy()
    {
        EventManager.HeartBeat -= OnHeartBeat;
    }

    private void OnHeartBeat()
    {
        lastHeartTime = Time.time;
        count = 0;
       SendMessage(Protocol.HeartBeat);
    }
    int count = 0;
    
    private float lastHeartTime=0;
   
    void CheckHeat()
    {
        if (client.onLine&&client.isLogin)
        {
            if (Time.time - lastHeartTime > 5)
            {
                count++;
                lastHeartTime = Time.time;
                Debug.Log("心跳超时一次");
                if (count >=3)
                {
                    count = 0;
                    
                    Debug.Log("心跳超时三次，已断线");
                    client.OnClose();
                }               
            }
        }             
    }

    public void AddEnvent(ByteBuffer buffer)
    {
        queue.Enqueue(buffer);
    }

    private void Update()
    {
        if (queue.Count > 0)
        {
            ByteBuffer buffer = queue.Dequeue();
            //把消息交给事件分发
            EventManager.Instance.OnMessage(buffer);
        }
        CheckHeat();
    }

    //ui调用的发送服务器的方法
    public void SendMessage(int protocol,string json)
    {
        client.SendMessage(protocol,json);
    }
    public void SendMessage(int protocol)
    {
        client.SendMessage(protocol);
    }
    public void SetOnLine(bool ison)
    {
        client.isLogin = ison;
    }
}
